package com.xp.agent.service.mem.impl;

import java.lang.management.ManagementFactory;
import java.util.logging.Logger;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import com.xp.agent.service.FullGcService;

public class FullGcServiceImpl implements FullGcService {

	private Logger log = Logger.getLogger("FullGcService");
	private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
	private ObjectName tenuredMBean;
	private int gcPreCount = 0;

	public FullGcServiceImpl() {
		try {
			tenuredMBean = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact");
		} catch (MalformedObjectNameException e) {
			log.info("this jvm does not support MarkSweepCompact");
		}
	}

	@Override
	public long collect() {
		int returnCount = 0;
		try {
			Integer sumGcCount = Integer.parseInt(mbs.getAttribute(tenuredMBean, "CollectionCount").toString());
			if (gcPreCount > 0) {
				returnCount = sumGcCount - gcPreCount;
			}
			gcPreCount = sumGcCount;
		} catch (Throwable e) {
			gcPreCount = 0;
		}
		return returnCount;
	}

}
